<?php

/**
 * @package Application_Acl
 * @author Cezar Zaleski e Reginaldo Júnior
 * @version 1.0.0
 */

/**
 *
 * @namespace
 *
 */
namespace Application\Acl;

/**
 *
 * @uses Zend\Mvc\MvcEvent
 * @uses User\Controller\Plugin\UserAuthentication
 * @uses Application\Acl\Autorizacao
 */
use Zend\Mvc\MvcEvent as MvcEvent, 
User\Controller\Plugin\UserAuthentication as AuthPlugin, 
Application\Acl\Autorizacao, 
Application\Auth\UsuarioAuth;

class PluginAutorizacao {
	protected $_session = null;
	protected $_tempoSession = 1800;
	protected $_acl = null;
	protected $_usuarioAuth = null;

	public function __construct() {
		$usuarioAuth = new UsuarioAuth ();
		$this->_session = $usuarioAuth->getLoggedUser ();
		$this->_usuarioAuth = $usuarioAuth;
	}
	public function preDispatch(MvcEvent $event) {
		if($this->_session){
			if($this->sessionTime()){
				$module = $event->getRouteMatch()->getParam('module');
				$submodule = $event->getRouteMatch()->getParam('submodule');
				$action = $event->getRouteMatch()->getParam('action');
				$this->_acl = $event->getApplication ()->getServiceManager()->get ( 'Application\Acl\Autorizacao' );
				if(!$this->_acl->verificaAutorizacao ($module.":".$submodule, $action, $this->_session->noPerfil)){
					$this->redirectHome($event);			
				}
			}else{
				$this->redirectHome($event);
				$this->_usuarioAuth->logout();
			}
		}else{
			$this->redirectHome($event);
		}
		
	}
	
	protected function sessionTime(){
		if((time() - $this->_session->inicioSessao) > $this->_tempoSession){
			return false;
		}
		$this->_session->inicioSessao = time();
		return true;
	}
	
	protected function redirectHome(MvcEvent $event) {
		$route = $event->getRouteMatch()->getMatchedRouteName();
		if($route !== 'home') {
			$this->_usuarioAuth->logout();
			$url = $event->getRouter()->assemble(array(), array("name"=> "home"));
			$event->getResponse()->getHeaders()->addHeaderLine ('Location', $url);
			$event->getResponse()->setStatusCode ( 302 );
			$event->getResponse()->sendHeaders ();
		}
	}
}
